package app.v1.schedulers;

import app.common.utils.YdApi;
import app.common.utils.cjt.CJtUtils;
import app.common.utils.cjt.vo.InventoryClassQueryVo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自动存货编码
 * 每十二分钟同步一次库存代码（将宜搭中的库存编码同步到畅捷通、同时同步到宜搭其他表单）
 * @author feizns
 * @since 2023/08/23
 */
@Component
public class AutoSynchronizeInventoryCode {

    /**
     * 自动库存同步代码
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void autoSynchronizeInventoryCode() {
        //宜搭中存货分类列表
        List<InventoryClassQueryVo> yiDaInventoryClass = YdApi.inventoryClass();
        //畅捷通存货分类列表
        List<InventoryClassQueryVo> inventoryClass = CJtUtils.inventoryClassQuery();
        //分析宜搭中存在但畅捷通中不存在的存货分类列表
        List<InventoryClassQueryVo> minus = minus(yiDaInventoryClass, inventoryClass);
        //同步到畅捷通
        minus.forEach(inventoryClazz -> {
            try {
                CJtUtils.inventoryClassCreate(inventoryClazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //同步到宜搭其他表单
        minus.forEach(vo -> {
            try {
                YdApi.yiDaUtils.forms.insert("FORM-2A666T61R8EDV81GBNHTXA18K32A2FB6QQELLH", Map.of("textField_lleqqa4w", vo.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * -
     * @param yiDaInventoryClass 易达库存类
     * @param inventoryClass 库存类
     * @return {@link List}<{@link InventoryClassQueryVo}>
     */
    private List<InventoryClassQueryVo> minus(List<InventoryClassQueryVo> yiDaInventoryClass, List<InventoryClassQueryVo> inventoryClass) {
        List<InventoryClassQueryVo> diff = new ArrayList<>();
        Map<String, InventoryClassQueryVo> cjtMap = inventoryClass.stream().collect(Collectors.toMap(InventoryClassQueryVo::getCode, Function.identity()));
        for (InventoryClassQueryVo vo : yiDaInventoryClass) {
            if ( !cjtMap.containsKey(vo.getCode()) )
                diff.add(vo);
        }
        return diff;
    }

    public static void main(String[] args) {
//        List<BatchGetFormDataByIdListResponseBody.BatchGetFormDataByIdListResponseBodyResult> list = YdApi.yiDaUtils.forms.getList("FORM-YU966T91OJH9G33C8WYU9BRJ64KB31UAH5WFLF");
//        for (BatchGetFormDataByIdListResponseBody.BatchGetFormDataByIdListResponseBodyResult data : list) {
//            System.out.println(JSON.toJSONString(data));
//        }

//        CJtUtils.inventoryClassQuery().forEach(System.out::println);
    }

}
